<template>
  <div class="universal-config-container">
    <div class="config-header">
      <h2>万能文档中心</h2>
      <div class="config-actions">
        <el-input v-model="searchQuery" placeholder="搜索配置" prefix-icon="Search" clearable @input="filterConfigs" />
        <el-button type="primary" @click="showAddConfigDialog">
          <el-icon>
            <Plus />
          </el-icon>添加新配置
        </el-button>
      </div>
    </div>

    <div class="config-content">
      <div v-if="filteredConfigs.length === 0" class="empty-config">
        <el-empty description="暂无配置项" />
      </div>

      <div v-else class="config-grid">
        <div v-for="config in filteredConfigs" :key="config.id" class="config-card">
          <div class="config-card-header">
            <div class="config-icon">
              <el-icon>
                <component :is="config.icon"></component>
              </el-icon>
            </div>
            <el-dropdown trigger="click" @command="handleCommand($event, config)" @click.stop>
              <span class="more-actions">
                <el-icon>
                  <MoreFilled />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="config-card-content">
            <h3 class="config-name">{{ config.name }}</h3>
            <p class="config-description">{{ config.description || '暂无描述' }}</p>
          </div>
          <div class="config-card-footer">
            <span class="config-date">创建于: {{ formatDate(config.createdDate) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑配置弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEditing ? '编辑文档' : '添加新文档'" :fullscreen="true"
      class="fullscreen-dialog">
      <div class="dialog-header">
        <h3 class="dialog-title">{{ currentConfig.name || '新文档' }}</h3>
        <div class="dialog-actions">
          <el-button type="text" @click="toggleFullscreen" class="fullscreen-toggle">
            <el-icon>
              <FullScreen />
            </el-icon>
          </el-button>
        </div>
      </div>

      <div class="split-layout">
        <!-- 左侧编辑区域 -->
        <div class="edit-area">
          <universal-doc-edit-tools
            v-model:configData="currentConfig"
            v-model:parameterBlocks="parameterBlocks"
            v-model:documentBlocks="documentBlocks"
            v-model:imageBlocks="imageBlocks"
            v-model:selectedTools="selectedTools"
            @compiled-content-updated="onCompiledContentUpdated"
          />
        </div>

        <!-- 右侧预览区域 -->
        <div class="preview-area">
          <div class="preview-header">
            <h3>预览效果</h3>
          </div>
          <universal-doc-preview-tools
            :configData="currentConfig"
            :parameterBlocks="parameterBlocks"
            :documentBlocks="documentBlocks"
            :imageBlocks="imageBlocks"
            :selectedTools="selectedTools"
            :toolList="toolList"
            :editorContent="editorContent"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveConfig">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="300px">
      <p>确定要删除配置"{{ currentConfig.name }}"吗？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, shallowRef } from 'vue';
import { Plus, Search, Setting, Document, ChatDotRound, DataAnalysis, MoreFilled, Link, FullScreen } from '@element-plus/icons-vue';
import { ElMessage, ElLoading } from 'element-plus';
import UniversalDocEditTools from '@/components/universalDoc/UniversalDocEditTools.vue';
import UniversalDocPreviewTools from '@/components/universalDoc/UniversalDocPreviewTools.vue';
import universalDocService, { ConfigItem } from '@/services/universalDocService';

interface DocumentBlock {
  type: string;
  title: string;
  content: string;
  rows: number;
  createdAt: number;
}

interface ParameterBlock {
  key: string;
  value: string;
  createdAt: number;
}

interface ImageBlock {
  url: string;
  name: string;
  createdAt: number;
}

interface ToolItem {
  id: string;
  name: string;
  description: string;
}

// 使用ref存储配置列表，从服务器加载
const configs = ref<ConfigItem[]>([]);
const isLoading = ref(false);

const searchQuery = ref('');
const dialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const isEditing = ref(false);
const currentConfig = ref<ConfigItem>({
  id: '',
  name: '',
  icon: 'Setting',
  description: '',
  content: '',
  htmlContent: '',
  compiledContent: '',
  createdDate: new Date(),
  agent_ids: [],
  params: {}
});

const documentBlocks = ref<DocumentBlock[]>([]);
const parameterBlocks = ref<ParameterBlock[]>([]);
const imageBlocks = ref<ImageBlock[]>([]);
const editorContent = ref<string>('');
const previewMode = ref(false);
const toolList = ref<ToolItem[]>([]);
const selectedTools = ref<string[]>([]);

// 根据搜索关键词过滤配置
const filteredConfigs = computed(() => {
  if (!searchQuery.value) return configs.value;
  const query = searchQuery.value.toLowerCase();
  return configs.value.filter(config =>
    config.name.toLowerCase().includes(query) ||
    (config.description && config.description.toLowerCase().includes(query))
  );
});

// 从服务器加载配置列表
const loadConfigList = async () => {
  try {
    isLoading.value = true;
    configs.value = await universalDocService.getConfigList();
    isLoading.value = false;
  } catch (error) {
    ElMessage.error('加载配置列表失败');
    isLoading.value = false;
  }
};

// 过滤配置方法
const filterConfigs = () => {
  // 搜索功能已通过计算属性实现
};

// 显示添加配置对话框
const showAddConfigDialog = () => {
  isEditing.value = false;
  currentConfig.value = {
    id: Date.now().toString(),
    name: '',
    icon: 'Setting',
    description: '',
    content: '',
    htmlContent: '',
    createdDate: new Date(),
    agent_ids: [],
    params: {}
  } as ConfigItem;
  documentBlocks.value = [];
  parameterBlocks.value = [];
  imageBlocks.value = [];
  dialogVisible.value = true;
};

// 编辑配置
const editConfig = (config: ConfigItem) => {
  isEditing.value = true;
  currentConfig.value = JSON.parse(JSON.stringify(config)) as ConfigItem; // 深拷贝
  
  try {
    const data = JSON.parse(config.content);
    parameterBlocks.value = data.parameters || [];
    documentBlocks.value = data.documents || [];
    imageBlocks.value = data.images || [];
    
    // 恢复选中的工具
    selectedTools.value = config.agent_ids || [];
  } catch (e) {
    ElMessage.error('配置解析失败');
    // 如果解析失败，重置所有块
    parameterBlocks.value = [];
    documentBlocks.value = [];
    imageBlocks.value = [];
    selectedTools.value = [];
  }
  
  dialogVisible.value = true;
};

// 处理下拉菜单命令
const handleCommand = (command: string, config: ConfigItem) => {
  if (command === 'edit') {
    editConfig(config);
  } else if (command === 'delete') {
    currentConfig.value = config;
    deleteDialogVisible.value = true;
  }
};

// 编译内容更新事件处理
const onCompiledContentUpdated = (content: string) => {
  editorContent.value = content;
};

// 监听对话框关闭事件，重置预览模式
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    previewMode.value = false;
  }
});

// 保存配置
const saveConfig = async () => {
  try {
    const loading = ElLoading.service({
      lock: true,
      text: '保存中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // 准备参数对象，基于参数块列表
    const params: Record<string, string> = {};
    parameterBlocks.value.forEach(param => {
      params[param.key] = param.value;
    });
    
    // 准备保存的数据
    currentConfig.value.content = JSON.stringify({
      parameters: parameterBlocks.value,
      documents: documentBlocks.value,
      images: imageBlocks.value
    });
    
    // 添加agent_ids和params
    currentConfig.value.agent_ids = selectedTools.value;
    currentConfig.value.params = params;
    
    // 如果是编辑，添加更新日期
    if (isEditing.value) {
      currentConfig.value.updatedDate = new Date();
    }
    
    // 调用服务保存配置
    await universalDocService.saveConfig(currentConfig.value);
    
    // 重新加载配置列表
    await loadConfigList();
    
    loading.close();
    dialogVisible.value = false;
    ElMessage.success('配置保存成功');
  } catch (error) {
    ElMessage.error('保存配置失败');
  }
};

// 确认删除
const confirmDelete = async () => {
  try {
    const loading = ElLoading.service({
      lock: true,
      text: '删除中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    await universalDocService.deleteConfig(currentConfig.value.id);
    
    // 更新本地列表
    configs.value = configs.value.filter(c => c.id !== currentConfig.value.id);
    
    loading.close();
    deleteDialogVisible.value = false;
    ElMessage.success('配置已删除');
  } catch (error) {
    ElMessage.error('删除配置失败');
  }
};

// 格式化日期，确保处理字符串或Date对象
const formatDate = (date: Date | string) => {
  if (!date) return '';
  if (typeof date === 'string') date = new Date(date);
  return date.toLocaleDateString('zh-CN');
};

// 添加全屏切换方法
const toggleFullscreen = () => {
  const dialog = document.querySelector('.fullscreen-dialog') as HTMLElement;
  if (!document.fullscreenElement) {
    dialog.requestFullscreen().catch(err => {
      console.error('全屏模式错误:', err);
    });
  } else {
    document.exitFullscreen();
  }
};

// 加载工具列表
const loadTools = async () => {
  // 模拟数据
  toolList.value = [
    { id: '1', name: '数据分析工具', description: '用于数据分析和可视化' },
    { id: '2', name: 'API测试工具', description: '用于测试RESTful API' },
    { id: '3', name: '代码生成器', description: '根据模板生成代码' },
  ];
};

// 在onMounted中加载初始数据
onMounted(() => {
  loadConfigList();
  loadTools();
});
</script>

<style scoped>
.universal-config-container {
  height: 100%;
  padding: 1rem;
  display: flex;
  flex-direction: column;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #e6e6e6;
}

.config-header h2 {
  margin: 0;
  color: #334155;
  font-weight: 600;
  font-size: 1.5rem;
}

.config-actions {
  display: flex;
  gap: 1rem;
}

.config-content {
  flex: 1;
  overflow-y: auto;
  padding: 1rem 0;
}

.config-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1.2rem;
}

.config-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 200px;
  cursor: pointer;
  border-top: 3px solid #6366F1;
}

.config-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.config-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background: linear-gradient(to right, #f9fafb, #f3f4f6);
}

.config-icon {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%);
  color: white;
  border-radius: 8px;
}

.config-icon .el-icon {
  font-size: 1.2rem;
}

.more-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 4px;
  cursor: pointer;
  color: #64748b;
}

.more-actions:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.config-card-content {
  flex: 1;
  padding: 0.5rem 1rem 1rem;
  overflow: hidden;
}

.config-name {
  margin: 0 0 0.5rem;
  font-size: 1.1rem;
  color: #1e293b;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.config-description {
  color: #64748b;
  margin: 0;
  font-size: 0.9rem;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.config-card-footer {
  padding: 0.75rem 1rem;
  background-color: #f8fafc;
  font-size: 0.8rem;
  color: #94a3b8;
  border-top: 1px solid #f1f5f9;
}

.empty-config {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

/* 预览控制按钮 */
.preview-controls {
  margin-bottom: 20px;
  text-align: right;
}

/* 全屏对话框样式 */
.fullscreen-dialog {
  margin: 0 !important;
  max-width: 100vw;
  height: 100vh;
}

.fullscreen-dialog .el-dialog__header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}

.fullscreen-dialog .el-dialog__body {
  height: calc(100vh - 110px);
  padding: 20px;
  overflow-y: auto;
}

.fullscreen-dialog .el-dialog__footer {
  padding: 10px 20px;
  border-top: 1px solid #eee;
  position: sticky;
  bottom: 0;
  background: white;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.dialog-title {
  margin: 0;
  color: #334155;
  font-weight: 600;
  font-size: 1.5rem;
}

.dialog-actions {
  display: flex;
  gap: 1rem;
}

.split-layout {
  display: flex;
  height: calc(100vh - 110px);
}

.edit-area {
  flex: 1;
  padding: 1rem;
}

.preview-area {
  flex: 1;
  padding: 1rem;
}

.preview-header {
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #e6e6e6;
}
</style>